package pers.cz.netty.retry;


import pers.cz.jefconfig.config.JefConfiguration;
import pers.cz.netty.config.NettyConfigItem;
import pers.cz.netty.exception.ErrorCode;
import pers.cz.netty.exception.NettyException;

/**
 * @program: PostGirl-panent
 * @description: 默认重试策略
 * @author: Cheng Zhi
 * @create: 2022-10-04 21:37
 **/
public class DefaultRetryPolicyImpl implements RetryPolicy {

    /**
     * 最大重试次数
     */
    private int maxRetryCount;

    /**
     * 默认最大间隔为两个小时,单位s
     */
    private long maxRetryIntervalue;

    public DefaultRetryPolicyImpl() {
        this.maxRetryCount = JefConfiguration.getInt(NettyConfigItem.NETTY_MAX_RETRY_COUNT, 13);
        this.maxRetryIntervalue = JefConfiguration.getLong(NettyConfigItem.NETTY_CONNECT_RETRY_INTERVALUE, 7200);
    }

    DefaultRetryPolicyImpl(int maxRetryCount, long maxRetryIntervalues) {

        if (maxRetryCount <= 0) {
            throw new NettyException(ErrorCode.PARAMTER_NOT_GREATER_ZERO_ERROR, "maxRetryCount");
        }

        if (maxRetryIntervalue <= 0) {
            throw new NettyException(ErrorCode.PARAMTER_NOT_GREATER_ZERO_ERROR, "maxRetryIntervalues");
        }

        this.maxRetryCount = maxRetryCount;
        this.maxRetryIntervalue = maxRetryIntervalues;
    }
    @Override
    public boolean allowRetry(int retryCount) {
        return retryCount <= maxRetryCount;
    }

    @Override
    public long retryIntervalue(int retryCount) {
        if (retryCount < 0) {
            retryCount = 0;
        }

        return Math.min(maxRetryIntervalue, 1 << retryCount);
    }
}
